//
//  BaseAnimViewController.m
//  YXLearnMasonry
//
//  Created by Rookie_YX on 16/10/27.
//  Copyright © 2016年 Rookie_YX. All rights reserved.
//

#import "BaseAnimViewController.h"

@interface BaseAnimViewController ()

@property (nonatomic, strong) UIView *greenView;
@property (nonatomic, strong) UIView *redView;
@property (nonatomic, strong) UIView *blueView;
@property (nonatomic, assign) CGFloat padding;

@end

@implementation BaseAnimViewController

- (void)viewDidLoad {
  [super viewDidLoad];
 
  UIView *greenView = UIView.new;
  greenView.backgroundColor = UIColor.greenColor;
  [self.view addSubview:greenView];
  
  UIView *redView = UIView.new;
  redView.backgroundColor = UIColor.redColor;
  [self.view addSubview:redView];
  
  UIView *blueView = UIView.new;
  blueView.backgroundColor = UIColor.blueColor;
  [self.view addSubview:blueView];
  self.greenView = greenView;
  self.redView = redView;
  self.blueView = blueView;
  
  // 使这三个控件等高
  self.padding = 10;
  CGFloat padding = self.padding;
  [greenView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(padding),
    make.left.equalTo(padding),
    make.right.equalTo(redView.mas_left).offset(-padding),
    make.bottom.equalTo(blueView.mas_top).offset(-padding).priorityLow(),
    // 三个控件等高
    make.height.equalTo(@[redView, blueView]);
    // 红、绿这两个控件等高
    make.width.equalTo(redView);
    make.height.lessThanOrEqualTo(self.view);
  }];
  
  [redView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.height.width.bottom.mas_equalTo(greenView);
    make.right.equalTo(-padding);
    make.left.equalTo(greenView.mas_right).offset(padding);
    make.height.equalTo(@[greenView, blueView]);
  }];
  
  [blueView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.height.equalTo(@[greenView, redView]);
    make.bottom.equalTo(-padding);
    make.left.equalTo(padding);
    make.right.equalTo(-padding);
  }];
  
  [self updateAnimated:NO];
  
  
  //  补充
  /**
   Masonry约束易忽略的技术点
   使用Masonry不需要设置控件的translatesAutoresizingMaskIntoConstraints属性为NO;
   防止block中的循环引用，使用弱引用（这是错误观点），在这里block是局部的引用，block内部引用self不会造成循环引用的
   __weak typeof (self) weakSelf = self;（没必要的写法）
   */
}

- (void)updateAnimated:(BOOL)animated {
  CGFloat padding = self.padding >= 350 ? 10 : 350;
  CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
  [self.blueView mas_updateConstraints:^(MASConstraintMaker *make) {
    make.bottom.mas_equalTo(-padding);
    make.top.mas_equalTo((screenHeight - 64) / 2 - 5);
    //    make.right.mas_equalTo(self.view.mas_right).offset(-padding);
  }];
  
  if (animated) {
    [self.view setNeedsUpdateConstraints];
    [self.view updateConstraintsIfNeeded];
    
    [UIView animateWithDuration:0.5 animations:^{
      [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
      self.padding = padding;
      [self updateAnimated:YES];
    }];
  } else {
    [self.view layoutIfNeeded];
    
    [self updateAnimated:YES];
  }
}
@end
